import React, { PureComponent } from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Select, Input, Tooltip } from 'antd';
import TableForm from './TableForm';
import { connect } from 'dva';
import style from './index.less';
import { message } from 'antd/lib/index';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalInst from './Modal';
import { AddressC, AdvancedSearch, ContentPackage, SecondHeaderC, InputC, SelectC, DATA_ENTRY, PrimaryC } from '../../../comps';

const { TextArea } = Input;
moment.locale('zh-cn');
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
@connect(({ tenantManageM, userM: user, globalM }) => ({
  tenantManageM,
  user,
  globalM,
}))
@Form.create()
export default class Station extends PureComponent {
  state = {
    titleModal: '新增',
    saveVisible: false,
    formItem: {},
    formItem2: {},
    gwqxSelect: [],
    userAccount: '',
    realValue: '',
    xyzhable: false,
    p11: undefined,
    c11: undefined,
    isReset: false, // 是否点击了重置
    currentPage: 1,
    numInPage: 10,
    userManageData: undefined, // 用户表格数据
    searchObj: {}, // 查询条件
    isUseReportFlag: '0', // 【是否使用报告】为1时：发行机构代码 必填
  };

  // 页面初始函数
  UNSAFE_componentWillMount = () => {
    // 查询全部岗位
    this.props.dispatch({
      type: 'tenantManageM/Search',
      payload: {},
    });
    // 下游租户数据
    this.props.dispatch({
      type: 'tenantManageM/sysOrgan',
      payload: {},
    });
    this.props.dispatch({
      type: 'tenantManageM/getScenes',
      payload: {},
    });
    this.props.dispatch({
      type: 'tenantManageM/getTemplate',
      payload: {},
    });
  };

  // 查询事件
  handleSearch = (e) => {
    let values = {};
    if (e && JSON.stringify(e) != '{}') {
      values = {
        search: e.postName.trim(),
      };
      this.setState(
        {
          currentPage: 1,
          isReset: false,
          searchObj: values,
        },
        () => {
          this.props.dispatch({
            type: 'tenantManageM/save',
            payload: { loading: true },
          });
          this.props.dispatch({
            type: 'tenantManageM/Search',
            payload: this.state.searchObj,
          });
        },
      );
    } else {
      values = {};
      this.setState(
        {
          currentPage: 1,
          isReset: false,
          searchObj: values,
        },
        () => {
          this.props.dispatch({
            type: 'tenantManageM/save',
            payload: { loading: true },
          });
          this.props.dispatch({
            type: 'tenantManageM/Search',
            payload: this.state.searchObj,
          });
        },
      );
    }
  };

  // 再次输入密码校验
  checkConfirm = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('userPassword')) {
      callback('两次输入的密码不匹配!');
    } else {
      callback();
    }
  };

  // 省份组件change事件
  onChange1 = (e) => {
    this.setState({
      p11: e.province,
      c11: e.city,
    });
  };

  // 新增点击事件
  handleTableSave = () => {
    const { form } = this.props;
    form.resetFields([
      'userAccount',
      'userAccount2',
      'name',
      'userPassword',
      'userPassword2',
      'userEmail',
      'description',
      'code',
      'xyxt',
      'xyzh',
      'province',
      'city',
      'address',
      'name2',
      'p11',
      'c11',
      'unsecuredAutomaticSettlement',
      'workbenchConfiguration',
      'reportScenario',
      'reportTemplate',
    ]);
    this.setState({
      titleModal: '新增',
      saveVisible: true,
      formItem: {},
      xyzhable: false,
      p11: undefined,
      c11: undefined,
      isUseReportFlag: '0',
    });
  };

  // 下游系统下拉框change事件
  handleSelectChange = (e) => {
    if (e == 'NULL') {
      this.props.form.setFieldsValue({
        xyzh: null,
      });
      this.setState({
        xyzhable: true,
      });
    } else {
      this.setState({
        xyzhable: false,
      });
    }
  };

  // 表格change事件
  changeReset = (current, pagesize) => {
    const { isReset } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        isReset: false,
      });
      return;
    }
    this.setState({
      currentPage: current,
      numInPage: pagesize,
    });
  };

  render() {
    const { form } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const {
      tenantManageM: { data, sysOrgan, sceneList, templateList },
      dispatch,
    } = this.props;
    const that = this;
    // 下游系统数据
    const downstreamSystem = [
      { title: 'MATIC', value: 'MATIC' },
      { title: 'NULL', value: 'NULL' },
    ];
    // 用户数据
    const userData = [];
    that.state.userManageData &&
      that.state.userManageData.forEach((item) => {
        userData.push({ title: item.userId, value: item.userId });
      });
    const table = {
      data,
      onDeleteFrom(item) {
        that.props.dispatch({
          type: 'tenantManageM/deleteUser',
          payload: item.id,
          callback: (res) => {
            if (res == 'success') {
              // 查询
              that.props.dispatch({
                type: 'tenantManageM/Search',
                payload: that.state.searchObj,
              });
            }
          },
        });
      },

      onEditFrom(item) {
        // 获取用户表格数据
        dispatch({
          type: 'tenantManageM/SearchUserData',
          payload: {
            tenantId: item.code,
          },
          callback: (type, res) => {
            if (type == 'success') {
              that.setState({
                userManageData: res,
              });
            }
          },
        });
        form.resetFields([
          'userAccount',
          'userAccount2',
          'name',
          'userPassword',
          'userPassword2',
          'userEmail',
          'description',
          'code',
          'xyxt',
          'xyzh',
          'province',
          'city',
          'address',
          'name2',
          'p11',
          'c11',
          'unsecuredAutomaticSettlement',
          'workbenchConfiguration',
          '',
          'reportScenario',
          'reportTemplate',
        ]);
        that.setState({
          titleModal: '编辑',
          saveVisible: true,
          formItem: {
            ...item,
            workbenchConfiguration: item.workbenchConfiguration ? item.workbenchConfiguration.split(',') : undefined,
          },
          userAccount: item.userAccount,
          xyzhable: false,
          p11: item.province,
          c11: item.city,
          unsecuredAutomaticSettlement: item.unsecuredAutomaticSettlement ? item.unsecuredAutomaticSettlement : '0',
        });
      },
    };
    const {
      globalM: {
        dataDictionary: { workbenchConfiguration = [] },
      },
    } = this.props;
    const workbenchConfigurationList = workbenchConfiguration.map((v) => ({ ...v, title: v.value, value: v.code }));
    const modal = {
      titleModal: that.state.titleModal,
      saveVisible: that.state.saveVisible,
      saveModal() {
        return (
          <Form className={style.formStyle}>
            <SecondHeaderC title={'租户'} />
            <Row style={{ marginTop: '6px' }}>
              <Col span={12}>
                <InputC
                  form={that.props.form} // form对象
                  dataIndex={'code'}
                  title={'账户'}
                  formItemLayout={formItemLayout}
                  initialValue={that.state.formItem.code || ''}
                  rules={[{ required: true, message: '请输入账户' }]}
                  disabled={that.state.titleModal == '编辑'}
                />
              </Col>
              <Col span={12}>
                <InputC
                  form={that.props.form} // form对象
                  dataIndex={'name'}
                  title={'租户名称'}
                  formItemLayout={formItemLayout}
                  initialValue={that.state.formItem.name || ''}
                  rules={[{ required: true, message: '请输入租户名称' }]}
                />
              </Col>
            </Row>
            {/* 省份 */}
            <AddressC
              form={form}
              provinceDataIndex={'p11'}
              cityDataIndex={'c11'}
              provInit={that.state.p11}
              cityInit={that.state.c11}
              onChange={that.onChange1}
              formItemLayout={formItemLayout}
              rules={[[{ required: true, message: '请选择省份' }], [{ required: true, message: '请选择城市' }]]}
            />

            {/* 详细地址 */}
            <Row style={{ marginTop: '6px' }}>
              <Col span={24}>
                <FormItem label='详细地址' labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                  {getFieldDecorator('address', { initialValue: that.state.formItem.address })(<TextArea style={{ minHeight: 30 }} placeholder='请输入' />)}
                </FormItem>
              </Col>
            </Row>

            {/* 2022/08/05迭代需求 */}
            <Row style={{ marginTop: '6px' }}>
              <Col span={12}>
                <SelectC
                  dataIndex='unsecuredAutomaticSettlement'
                  form={that.props.form}
                  title='交收方式'
                  showSearch={false}
                  initialValue={that.state.formItem.unsecuredAutomaticSettlement || '2'}
                  formItemLayout={formItemLayout}
                  optionTitle={true}
                  dataSource={[
                    {
                      title: '自动交收',
                      value: '1',
                    },
                    {
                      title: '手动交收',
                      value: '2',
                    },
                  ]}
                />
              </Col>
              <Col span={12}>
                <SelectC
                  isMultiple={true}
                  allowClear={true}
                  dataIndex='workbenchConfiguration'
                  form={that.props.form}
                  title='工作台配置'
                  showSearch={false}
                  initialValue={that.state.formItem.workbenchConfiguration || undefined}
                  formItemLayout={formItemLayout}
                  optionTitle={true}
                  dataSource={workbenchConfigurationList || []}
                />
              </Col>
            </Row>
            {/* 2022-04-22 需求 */}
            <Row>
              <Col span={12}>
                <SelectC
                  form={that.props.form} // form对象
                  dataIndex={'reportScenario'}
                  title={'压力测试报告情景'}
                  formItemLayout={formItemLayout}
                  dataSource={sceneList}
                  allowClear={true}
                  initialValue={that.state.formItem.reportScenario || undefined}
                />
              </Col>
              <Col span={12}>
                <SelectC
                  form={that.props.form} // form对象
                  dataIndex={'reportTemplate'}
                  title={'压力测试报告模板'}
                  formItemLayout={formItemLayout}
                  dataSource={templateList}
                  allowClear={true}
                  initialValue={that.state.formItem.reportTemplate || undefined}
                />
              </Col>
            </Row>
            <Row style={{ marginTop: '6px' }}>
              <Col span={24}>
                <FormItem label='描述' labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                  {getFieldDecorator('description', { initialValue: that.state.formItem.description })(<TextArea style={{ minHeight: 60 }} placeholder='请输入' />)}
                </FormItem>
              </Col>
            </Row>

            <SecondHeaderC title={'管理员'} />

            <Row style={{ marginTop: '6px' }}>
              <Col span={12}>
                {that.state.titleModal == '编辑' ? (
                  <SelectC
                    dataIndex='userAccount2'
                    form={that.props.form}
                    title='账户'
                    showSearch={false}
                    initialValue={that.state.formItem.userAccount || ''}
                    formItemLayout={formItemLayout}
                    dataSource={userData}
                    optionTitle={true}
                  />
                ) : (
                  <InputC
                    form={that.props.form} // form对象
                    dataIndex={'userAccount'}
                    title={'账户'}
                    formItemLayout={formItemLayout}
                    initialValue={that.state.formItem.userAccount || ''}
                    rules={[{ required: true, message: '请输入账户' }]}
                  />
                )}
              </Col>
              <Col span={12}>
                {that.state.titleModal == '编辑' ? null : (
                  <InputC
                    form={that.props.form} // form对象
                    dataIndex={'name2'}
                    title={'姓名'}
                    formItemLayout={formItemLayout}
                    initialValue={that.state.formItem2.name || ''}
                    rules={[{ required: true, message: '请输入姓名' }]}
                  />
                )}
              </Col>
            </Row>

            <Row style={{ marginTop: '6px' }}>
              <Col span={12}>
                {that.state.titleModal == '编辑' ? null : (
                  <FormItem
                    label={
                      <span>
                        密码&nbsp;
                        <Tooltip title='密码长度8-128，且至少包含数字、大写字母、小写字母、特殊字符四类中的三类！'>
                          <QuestionCircleOutlined />
                        </Tooltip>
                      </span>
                    }
                    {...formItemLayout}
                  >
                    {getFieldDecorator('userPassword', {
                      initialValue: that.state.formItem2.userPassword,
                      rules: [
                        { required: true, message: '请输入密码' },
                        {
                          pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,128}$/,
                          message: '输入密码格式不正确！',
                        },
                      ],
                      validateTrigger: 'onBlur',
                    })(<Input placeholder='请输入' />)}
                  </FormItem>
                )}
              </Col>
              <Col span={12}>
                {that.state.titleModal == '编辑' ? null : (
                  <FormItem label='确认密码' {...formItemLayout}>
                    {getFieldDecorator('userPassword2', {
                      initialValue: that.state.formItem2.userPassword,
                      rules: [{ required: true, message: '请再次输入密码' }, { validator: that.checkConfirm }],
                      validateTrigger: 'onBlur',
                    })(<Input placeholder='请输入' />)}
                  </FormItem>
                )}
              </Col>
            </Row>

            <Row style={{ marginTop: '6px' }}>
              <Col span={12}>
                {that.state.titleModal == '编辑' ? null : (
                  <FormItem label='邮箱' {...formItemLayout}>
                    {getFieldDecorator('userEmail', {
                      initialValue: that.state.formItem2.userEmail,
                      rules: [
                        {
                          type: 'email',
                          message: '请输入正确格式的邮箱地址',
                        },
                      ],
                      validateTrigger: 'onBlur',
                    })(<Input placeholder='请输入' />)}
                  </FormItem>
                )}
              </Col>
            </Row>
          </Form>
        );
      },
      // 确认点击事件
      confirmRevise(e) {
        e.preventDefault();
        const { form } = that.props;
        form.validateFields(
          [
            'userAccount',
            'name',
            'userPassword',
            'userPassword2',
            'userEmail',
            'description',
            'name2',
            'code',
            'xyxt',
            'xyzh',
            'province',
            'city',
            'address',
            'p11',
            'c11',
            'userAccount2',
            'unsecuredAutomaticSettlement',
            'workbenchConfiguration',
            'reportScenario',
            'reportTemplate',
          ],
          (err, fieldsValue) => {
            if (err) return;
            const postAuthority = [];
            that.state.gwqxSelect.map((item, i) => {
              return postAuthority.push({ id: item });
            });
            if (that.state.titleModal == '新增') {
              // 新增
              const values = {
                name: fieldsValue.name,
                code: fieldsValue.code,
                description: fieldsValue.description,
                downstreamSys: fieldsValue.xyxt,
                organCode: fieldsValue.xyzh,
                address: fieldsValue.address,
                province: that.state.p11,
                city: that.state.c11,
                user: {
                  userAccount: fieldsValue.userAccount,
                  name: fieldsValue.name2,
                  userPassword: fieldsValue.userPassword,
                  userEmail: fieldsValue.userEmail,
                },
                unsecuredAutomaticSettlement: fieldsValue.unsecuredAutomaticSettlement,
                workbenchConfiguration: fieldsValue.workbenchConfiguration ? fieldsValue.workbenchConfiguration.join(',') : undefined,
                reportScenario: fieldsValue.reportScenario,
                reportTemplate: fieldsValue.reportTemplate,
              };
              that.props.dispatch({
                type: 'tenantManageM/save',
                payload: { loading: true },
              });
              that.props.dispatch({
                type: 'tenantManageM/saveTable',
                payload: values,
                callback: (res) => {
                  if (res == 'success') {
                    that.setState({
                      saveVisible: false,
                      userAccount: '',
                    });
                    // 查询
                    that.props.dispatch({
                      type: 'tenantManageM/Search',
                      payload: that.state.searchObj,
                    });
                  }
                },
              });
            } else {
              // 编辑
              let values = {
                id: that.state.formItem.id,
                name: fieldsValue.name,
                code: fieldsValue.code,
                description: fieldsValue.description,
                downstreamSys: fieldsValue.xyxt,
                organCode: fieldsValue.xyzh,
                address: fieldsValue.address,
                province: that.state.p11,
                city: that.state.c11,
                user: {
                  userAccount: fieldsValue.userAccount2,
                },
                unsecuredAutomaticSettlement: fieldsValue.unsecuredAutomaticSettlement,
                workbenchConfiguration: fieldsValue.workbenchConfiguration?.length > 0 ? fieldsValue.workbenchConfiguration.join(',') : undefined,
                reportScenario: fieldsValue.reportScenario,
                reportTemplate: fieldsValue.reportTemplate,
              };
              if (values.workbenchConfiguration === '') delete values.workbenchConfiguration;
              that.props.dispatch({
                type: 'tenantManageM/save',
                payload: { loading: true },
              });
              that.props.dispatch({
                type: 'tenantManageM/sysUpdate',
                payload: values,
                callback: (res) => {
                  if (res == 'success') {
                    that.setState({
                      saveVisible: false,
                      userAccount: '',
                    });
                    // 查询
                    that.props.dispatch({
                      type: 'tenantManageM/Search',
                      payload: that.state.searchObj,
                    });
                  }
                },
              });
            }
          },
        );
      },
      // 取消点击事件
      cancel() {
        that.setState({
          saveVisible: false,
          userAccount: '',
        });
      },
    };
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'postName',
          title: '关键字',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
        },
      ],
      // 点击查询按钮
      onQuery: (e) => {
        this.handleSearch(e);
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          isReset: true,
          searchObj: {},
        });
      },
    };
    return (
      <ContentPackage
        title='租户信息'
        contentHtml={
          <div>
            <div style={{ marginBottom: '10px' }}>
              <AdvancedSearch {...searchProps} />
            </div>
            <PrimaryC title='新增' style={{ margin: '0 10px 10px 10px' }} onClick={this.handleTableSave} />
            <TableForm {...table} changeReset={this.changeReset} currentPage={this.state.currentPage} numInPage={this.state.numInPage} />
            <ModalInst {...modal} />
          </div>
        }
      />
    );
  }
}
